package dbchatting;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ColorChooserUI;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;
import java.awt.Dimension;

public class SingleChatClient extends JFrame implements Runnable {

	Socket socket = null;
	BufferedWriter send = null;
	BufferedReader receive = null;
	boolean threadFlag = false;
	StringBuilder data = new StringBuilder();
	int portNum = 4444;

	static String driver = "oracle.jdbc.driver.OracleDriver";
	static String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
	static String id = "hr";
	static String password = "hr";

	Connection con;

	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JTextField serverIP;
	private JButton btnLogout;
	private JButton btnLogin;
	private JButton btnNewButton_2;
	private JTextField message;
	private JScrollPane scrollPane;
	private JTextPane result;
	private JTextField tit;
	private JPanel panel_2;
	private JLabel lblNewLabel;
	private JPanel panel_3;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SingleChatClient frame = new SingleChatClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SingleChatClient() {

		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				serverDisconnect();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
		contentPane.add(getPanel_2(), BorderLayout.SOUTH);

		try {

			// 데이터베이스 연결 테스트
			// try {
			Class.forName(driver).newInstance();
			System.out.println("드라이버가 로딩되었습니다.");

			con = DriverManager.getConnection(url, "hr", "hr");
			System.out.println("데이터베이스가 정상적으로 연결됨");

			InetAddress ia = InetAddress.getLocalHost();
			setTitle("IP주소 : " + ia.getHostAddress() + " port번호 : " + portNum);

		} catch (Exception e) {

		}
	}

	@Override
	public void run() {

		try {
			socket = new Socket(serverIP.getText(), portNum);

			OutputStream os = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			send = new BufferedWriter(osw);

			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			receive = new BufferedReader(isr);

			threadFlag = true;

			while (threadFlag) {
				String str = receive.readLine();
				if ("\tserverdown".equals(str)) {
					threadFlag = false;
					sendMsg(str);
					break;
				} else if ("\tkill".equals(str)) {
					threadFlag = false;
					break;
				} else {
					dataSet("수신 : " + str);
				}
			}

			dataSet("접속이 해제되었습니다.<br>");

			receive.close();
			isr.close();
			is.close();
			send.close();
			osw.close();
			os.close();
			socket.close();

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public void dataSet(String d) {// JTextPane에 문자열을 추가하기 위해서
		data.append(d);// StringBuilder에 String을 추가
		data.append("<br/>");
		result.setText(data.toString());
	}

	public void serverConnect() {// 접속버튼을 클릭하면 호출
		try {
			dataSet("서버에 접속 되었습니다.");
			Thread t = new Thread(this);
			t.start();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public void serverDisconnect() {// 접속해제버튼이나 JFrame의 종료버튼이 클릭되면
		threadFlag = false;
		try {
			send.write("\tkill");
			send.newLine();
			send.flush();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	public void sendMsg(String ms) {
		try {
			send.write(ms);
			send.newLine();
			send.flush();
			dataSet("<font color = 'blue'> 나 :" + ms + "</font>");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getBtnLogout());
			panel.add(getServerIP());
			panel.add(getBtnLogin());
		}
		return panel;
	}

	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getBtnNewButton_2(), BorderLayout.EAST);
			panel_1.add(getMessage(), BorderLayout.CENTER);
		}
		return panel_1;
	}

	private JTextField getServerIP() {
		if (serverIP == null) {
			serverIP = new JTextField();
			serverIP.setText("192.168.10.130");
			serverIP.setColumns(10);
		}
		return serverIP;
	}

	private JButton getBtnLogout() {
		if (btnLogout == null) {
			btnLogout = new JButton("접속해제");
			btnLogout.setEnabled(false);
			btnLogout.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnLogin.setEnabled(true);
					btnLogout.setEnabled(false);
					serverDisconnect();
				}
			});
		}
		return btnLogout;
	}

	private JButton getBtnLogin() {
		if (btnLogin == null) {
			btnLogin = new JButton("서버접속");
			btnLogin.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					try {
						String sql = "select * from dbchatting order by serial asc";
						PreparedStatement pstmt = con.prepareStatement(sql);
						ResultSet rs = pstmt.executeQuery();
						while (rs.next()) {
							String i = rs.getString("mid");
							String e = rs.getString("content");
							String ie = i + " : " + e;

							dataSet(ie);

						}
						rs.close();
						pstmt.close();

					} catch (Exception ex) {
						ex.printStackTrace();
					}
					btnLogin.setEnabled(false);
					btnLogout.setEnabled(true);
					serverConnect();
				}
			});
		}
		return btnLogin;
	}

	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("메시지전송");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					insert();
				}
			});
		}
		return btnNewButton_2;
	}

	public void insert() {

		try {
			String str = message.getText();
			// sendMsg(str);
			// message.setText("");

			String c = serverIP.getText();
			String a = tit.getText();
			// String b = message.getText();
			String sql = "insert into dbchatting(serial, ip, mid, content) values(db_serial.nextval,?,?,?)";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1, c);
			pstmt.setString(2, a);
			pstmt.setString(3, str);

			pstmt.executeUpdate();

			message.setText("");
			//
			sendMsg(str);
			// if (gbm.select !=null)
			// gbm.select.setData();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}

	}

	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						String str = message.getText();
						insert();
						message.setText("");
					} else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
						message.setText("");
					}
				}
			});
			message.setColumns(15);
		}
		return message;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}

	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}

	private JTextField getTit() {
		if (tit == null) {
			tit = new JTextField();
			tit.setColumns(7);
		}
		return tit;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.add(getLblNewLabel());
			panel_2.add(getTit());
			panel_2.add(getPanel_3());
			panel_2.add(getPanel_1());
		}
		return panel_2;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("닉네임:");
		}
		return lblNewLabel;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
		}
		return panel_3;
	}
}
